<?php

namespace App\Http\Controllers;

//use Illuminate\Http\Request;
use Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Book;
use App\Models\Shudan;
use App\Models\UsersReg;
use App\Models\BooksReview;
use Session;
use Redirect;

class ShudanController extends Controller
{

    public function addshudan()
    {
        //增加书单
        return view('books.layouts.addshudan');
    }

    public function saveshudan()
    {
        //获得用户的uid
        //$name = Session::get('name');
        $uid = Session::get('nameid'); 

        //增加书单
        $shudan = new Shudan;

        $shudan -> uid = $uid;
        $shudan -> biaoti = trim(request::input('biaoti'));
        $shudan -> jieshao = request::input('jieshao');

        $shudanarray = request::input('shudanlist');

        

        //把数组变成字串，使用逗号（,）分割
        //count($shudanarray) 为数组的个数
        // $shudanlist ='';
        //  for($i=0; $i<count($shudanarray); $i++){
        //     if($shudanarray[$i] != ''){
        //         if($shudanlist!=''){
        //             $shudanlist = $shudanlist . ',' .$shudanarray[$i];
        //         }else{
        //             //第一个符号不是逗号（,）
        //             $shudanlist = $shudanarray[$i];
        //         }
        //     }
        // }

        $shudanarray = array_filter($shudanarray); // 去掉空数组
        $shudanlist = implode(',', $shudanarray); //数组变成字串
        
        //整理字符串，只保留数字(书籍编号)
        $shudanlist = str_replace('http://www.yedushu.com/info/', '', $shudanlist);
        $shudanlist = str_replace('/', '', $shudanlist);
        $shudanlist = str_replace(' ', '', $shudanlist);

        //去除非数字的字符的数组
        $arr = explode(',', $shudanlist);
        foreach($arr as $k => $v) {
            if(!is_numeric($v)) 
                unset($arr[$k]);
        }
        //去除重复的数组，重复的字符只保留一个
        $arr = array_unique($arr); 
        $arr = array_merge($arr);//重新排序数组下标

        $shudanlist = implode(',', $arr); // 用逗号分割的字串

        //判断添加的书籍是否存在,不存在则从数组里去掉
        for($i=0; $i<count($arr); $i++){
            if( empty($books = Book::find($arr[$i])) ){
                $shudanlist = str_replace($arr[$i], '', $shudanlist);
            }
        }

        // 过滤空数组
        $arr = explode(',', $shudanlist);        
        $arr = array_filter($arr); // 去掉空数组
        $shudanlist = implode(',', $arr); // 用逗号分割的字串

        $shudan -> shudanlist = $shudanlist;
        $shudan -> add_time = time(); //获取当前时间戳
        $shudan -> last_time = time();

        //如果没有添加成功的书单，不保存
        if($shudanlist != ''){
            $shudan -> save();
            return Redirect::to('shudaninfo/'. $shudan->id);
        }
        else{
            return Redirect::back(); //返回添加页面
        }

    }

    public function shudaninfo($id)
    {
        
        $shudans = Shudan::find($id);

        //书单不存在跳转到 404页面
        if(empty($shudans)){
            abort(404);
        }

        //记录书单浏览次数
        $shudans->click_count = $shudans->click_count + 1;
        $shudans->save();

        //显示书单内容
        $shudans = Shudan::where('id', $id)->get();
        foreach ($shudans as $shudan) {
            //得到会员资料
            $shudan['users'] = $shudan->hasOnUsersReg;
        }
        $shudanlist = $shudan->shudanlist;
        $arr = explode(',', $shudanlist); 
        //得到书单对应的书籍信息
        for($i=0; $i<count($arr); $i++){
            $books[$i] = Book::find($arr[$i]);            
        }

        $shudanlists = Shudan::limit(26)->orderBy('last_time', 'desc')->get();

        return view('books.layouts.shudaninfo',array(
            'shudan' => $shudan,
            'shudanlists' => $shudanlists,
            'books'   => $books
            ));
    }

    public function remove($shudanid,$bookid)
    {   
        //删除书单列表里的图书
        $shudans = Shudan::find($shudanid);
        //判断是否删除自己的书单
        if(Session::get('nameid') == $shudans->uid) {
        $shudanlist = $shudans -> shudanlist;
        //替换（删除）书单列表中的的图书
        $shudanlist = str_replace($bookid, '', $shudanlist);
        //字串转成数组，为了去掉空数组
        $arr = explode(',', $shudanlist); 
        $arr = array_filter($arr); // 去掉空数组
        $shudanlist = implode(',', $arr); // 用逗号分割的字串

        $shudans -> shudanlist = $shudanlist;
        $shudans-> save();

        return Redirect::back();
        }
        else {
            return '您没有删除权限！';
        }
    }

    public function edit($shudanid)
    {
        //编辑书单
        $shudans = Shudan::find($shudanid);
        //判断是否编辑自己的书单
        if(Session::get('nameid') == $shudans->uid) {
        return view('books.layouts.editshudan',array(
            'shudans' => $shudans
            ));
        }
        else{
            return '您没有编辑权限!';
        }
    }

    public function saveeditshudan($shudanid)
    {
        //保存编辑书单
        $shudans = Shudan::find($shudanid);

        $shudans -> biaoti = trim(request::input('biaoti'));
        $shudans -> jieshao = request::input('jieshao');

        //如果有增加书单
        if(request::input('shudanlist'))
        {
            $shudanarray = request::input('shudanlist');
            $shudanarray = array_filter($shudanarray); // 去掉空数组
            $shudanlist = implode(',', $shudanarray); //数组变成字串
            //整理字符串，只保留数字(书籍编号)
            $shudanlist = str_replace('http://www.yedushu.com/info/', '', $shudanlist);
            $shudanlist = str_replace('/', '', $shudanlist); //替换可能存在的/
            $shudanlist = str_replace(' ', '', $shudanlist); //替换可能存在的空格

            //已有的书单和新添加的书单合并
            $shudanlist = $shudans -> shudanlist . ',' . $shudanlist;

            //去除非数字的字符的数组
            $arr = explode(',', $shudanlist);
            foreach($arr as $k => $v) {
                if(!is_numeric($v)) 
                    unset($arr[$k]);
            }
            //去除重复的数组，重复的字符只保留一个
            $arr = array_unique($arr); 
            $arr = array_merge($arr);//重新排序数组下标
            $shudanlist = implode(',', $arr); // 用逗号分割的字串

            //判断添加的书籍是否存在,不存在则从数组里去掉
            for($i=0; $i<count($arr); $i++){
                if( empty($books = Book::find($arr[$i])) ){
                    $shudanlist = str_replace($arr[$i], '', $shudanlist);
                }
            }
            // 过滤空数组
            $arr = explode(',', $shudanlist);        
            $arr = array_filter($arr); // 去掉空数组
            $shudanlist = implode(',', $arr); // 用逗号分割的字串

            $shudans -> shudanlist = $shudanlist;
            $shudans -> last_time = time(); //获取当前时间戳
            }
        else
        {
            //没添加书单编辑一次，去掉书单里可能已经没有的书籍
            $shudanlist =$shudans -> shudanlist;
            //去除重复的数组，重复的字符只保留一个            
            $arr = explode(',', $shudanlist);
            $arr = array_unique($arr); 
            $arr = array_merge($arr);//重新排序数组下标
            $shudanlist = implode(',', $arr); // 用逗号分割的字串

            //判断添加的书籍是否存在,不存在则从数组里去掉
            for($i=0; $i<count($arr); $i++){
                if( empty($books = Book::find($arr[$i])) ){
                    $shudanlist = str_replace($arr[$i], '', $shudanlist);
                }
            }
            // 过滤空数组
            $arr = explode(',', $shudanlist);        
            $arr = array_filter($arr); // 去掉空数组
            $shudanlist = implode(',', $arr); // 用逗号分割的字串
        }

        $shudans -> save();

        return Redirect::to('shudaninfo/'. $shudans->id);
    }

    public function ushudanlist($uid)
    {
        //会员自己的书单列表
        $shudans = Shudan::where('uid', $uid)->orderBy('last_time', 'desc')->paginate(10);

        //if(count($shudans)==0){
            //本会员没有后书单
            //return '没有书单';
        //}

        foreach ($shudans as $shudan) {
             //得到会员资料
            $shudan['users'] = $shudan->hasOnUsersReg;
        }

        foreach ($shudans as $shudan) {
            //得到书单对应的书籍信息
            $shudanlist = $shudan->shudanlist;
            $arr = explode(',', $shudanlist);
            $pic = 1;
            for($i=0; $i<count($arr); $i++){                
                $books[$i] = Book::find($arr[$i]);
                $pic = $pic + 1;
                if($pic>14){
                    //显示14张书籍图片
                    break;
                }          
            }
            $shudan['shudanlsits'] = $books;
            $shudan['geshu'] = count($arr); //统计书单里书籍的数量

            $books = array(); // 下次赋值时清空数组
        }

        // if(empty($books)){
        //     //对应的书籍为空，也就是没书单
        //     //return '没有书单';
        //     $books = null;
        // }

        //获得用户信息
        $users = UsersReg::find($uid);

        //书单个数
        $shudangeshu = count(Shudan::where('uid',$uid)->get());
        //长书评个数
        $changshupinggeshu = count(BooksReview::where('uid',$uid)->get());
        //总计
        $zongji = $shudangeshu + $changshupinggeshu;

        return view('books.layouts.ushudanlist', array(
            'users'   => $users,
            'shudans' => $shudans,
            //'books'   => $books,
            'shudangeshu' => $shudangeshu,
            'changshupinggeshu' => $changshupinggeshu,
            'zongji'  => $zongji
            ));
    }

    public function shudanlist()
    {
        //显示全部书单列表
        $shudans = Shudan::orderBy('last_time', 'desc')->paginate(10);

        foreach ($shudans as $shudan) {
             //得到会员资料
            $shudan['users'] = $shudan->hasOnUsersReg;
        }

        foreach ($shudans as $shudan) {
            //得到书单对应的书籍信息
            $shudanlist = $shudan->shudanlist;
            $arr = explode(',', $shudanlist);
            $pic = 1;
            for($i=0; $i<count($arr); $i++){                
                $books[$i] = Book::find($arr[$i]);
                $pic = $pic + 1;
                if($pic>14){
                //超过14张，显示14张书籍图片
                     break;
                }
            }
            $shudan['shudanlists'] = $books; // 获得对应的图书信息            
            $shudan['geshu'] = count($arr); //统计书单里书籍的数量

            $books = array(); // 下次赋值时清空数组
        }


       

        //显示推荐书单列表导航
        $shudanls = Shudan::limit(30)->orderBy('last_time', 'desc')->get();
        //书单总数
        $shudanzongji =count(Shudan::all());

        return view('books.layouts.shudanlist', array(
            'shudans' => $shudans,
            'shudanls' => $shudanls, //显示推荐书单列表导航
            'shudanzongji' => $shudanzongji
            ));
    }
}
